package gupao.concurrency.simpleweb;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/tciword/rpt")
public class TciWordApiMock {

    static char SIMU_ERROR_WORD = UUID.randomUUID().toString().charAt(0);

    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }

    @GetMapping("/single/{word}")
    public String singleWordReport(@PathVariable String word){
        TciWordData data = getTciWordData(word);
        return data == null ? Resp.failResp("Not Existed") : Resp.successResp(data);
    }

    private TciWordData getTciWordData(String word){
        if(!StringUtils.hasText(word) || Objects.equals(word.charAt(0), SIMU_ERROR_WORD)){
            Utils.sleepIgnoreExp(3);
            return null;
        }
        Utils.sleepIgnoreExp(8);
        Random r = new Random();
        return TciWordData.builder()
                .bidword(word)
                .click((long)r.nextInt(100000))
                .comp((long)r.nextInt(100000))
                .cost((long)r.nextInt(9900))
                .cpc((long)r.nextInt(9900))
                .ctr(r.nextFloat())
                .cvr(r.nextFloat())
                .build();
    }
}
